<?php
/**
 * @filesource modules/article/controllers/IndexController.php
 * @author Tran Van Hoang
 * @abstract : List of actions in order
 *   - new
 *   - view
 *   - edit
 *   - delete
 *   - search
 *   - bulk
 *   - translate
 *   
 */ 
class Article_IndexController extends Clu_Controller_Action_Hvn
{
	public $m; //model

	public function init()
	{
		$this->m = new article_Model_Service();
		parent::init();
	}
	
	public function newAction() 
    {
        $this->view->form = new Form_Article();
        $this->view->form->cluBuild(array('action' => 'new','view' => $this->view));
//        die_a($this->view->form);
        
        if ($this->_request->isPost() && $this->view->form->isValid($_POST)) 
        {
            $this->m->insertRaw($this->_request->getParams(), false);
            $lastInsertId = $this->db->lastInsertId();
            //forward to avoid refreshing
            $this->_forward("success", 'index' , 'article', array('lastInsertId' => $lastInsertId, 'lang' => 'en' ) );
            return;
        }
        $loginRequest = array(
                                'module' => 'user',
                                'controller' => 'block',
                                'action' => 'login',
                                'regionId' => 1,
                                'boxWeight' => 1,
								'theme' => 'second'
                );
		$this->addMiniAction($loginRequest);
/*			
		$OnlineSupportRequest = array(
				'module' => 'hvn',
				'controller' => 'block',
				'action' => 'onlineSupport',
				'regionId' => 5,
				'boxWeight' => 2,
		);
		$this->addMiniAction($OnlineSupportRequest);
	
		$infoSupportRequest = array(
				'module' => 'common',
				'controller' => 'block',
				'action' => 'infoSupport',
				'regionId' => 5,
				'boxWeight' => 3,
		);
		$this->addMiniAction($infoSupportRequest);
		
		$mapRequest = array(
                            'module' => 'hvn',
                            'controller' => 'block',
                            'action' => 'mapVietnam',
                            'regionId' => 6,
                            'boxWeight' => 1,
                );
		$this->addMiniAction($mapRequest);
*/		
        $this->renderToHolder('index/new.phtml', false, null, 4, 1); 
    }

    
    public function viewAction()
    {
    	$id = $this->_request->getParam("id");
    	if (!$a = $this->m->getArticleData($id))
        {
            $this->view->errorMessage = t(504);
            $this->renderToHolder('common/error.phtml');
            return;
        }
//        die_a($a);
        if ($a['article_language'] != Zend_Registry::get('viewLang'))
            $this->view->errorMessage = t(505);

        $this->view->article = $a;
        
        $loginRequest = array(
                                'module' => 'user',
                                'controller' => 'block',
                                'action' => 'login',
                                'regionId' => 1,
                                'boxWeight' => 1,
								'theme' => 'second'
                );
		$this->addMiniAction($loginRequest);
		
		$OnlineSupportRequest = array(
				'module' => 'hvn',
				'controller' => 'block',
				'action' => 'onlineSupport',
				'regionId' => 5,
				'boxWeight' => 2,
		);
		$this->addMiniAction($OnlineSupportRequest);
		
		$infoSupportRequest = array(
				'module' => 'common',
				'controller' => 'block',
				'action' => 'infoSupport',
				'regionId' => 5,
				'boxWeight' => 3,
		);
		$this->addMiniAction($infoSupportRequest);
		
		$mapRequest = array(
                            'module' => 'hvn',
                            'controller' => 'block',
                            'action' => 'mapVietnam',
                            'regionId' => 6,
                            'boxWeight' => 1,
                );
		$this->addMiniAction($mapRequest);
		
        $this->renderToHolder('index/view.phtml', false, null, 4, 1); 
    }
    
	public function editAction()
	{
        $form = new Form_Article();
        $form->cluBuild(array ('action' => 'edit','view' => $this->view));
    	$id = $this->_request->getParam("id");

    	if (!$a = $this->m->findByPrimary($id))
        {                
            $this->view->errorMessage = t(504);
            $this->renderToHolder('common/error.phtml');
            return;                                                                                                                                                                   
        }
        //everything's fine. Continue editing
        //populate the data with 
		if (!$this->_request->isPost())
            $form->populate($a->toArray());
		
        else if ($form->isValid($_POST))
        {	
            if ($this->m->saveRaw($a, $form->getValues(), $id, false))
            {
                $this->view->operation = t(506);
                $this->renderToHolder('common/success.phtml');
                return;
            }
            else 
                $this->view->errorMessage = t(507);
        }
        else 
        	$this->view->errorMessage = t(71);
        $this->view->form = $form;
        $this->view->id = $id;
        
        $loginRequest = array(
                                'module' => 'user',
                                'controller' => 'block',
                                'action' => 'login',
                                'regionId' => 1,
                                'boxWeight' => 1,
								'theme' => 'second'
                );
		$this->addMiniAction($loginRequest);
/*		
		$OnlineSupportRequest = array(
				'module' => 'hvn',
				'controller' => 'block',
				'action' => 'onlineSupport',
				'regionId' => 5,
				'boxWeight' => 2,
		);
		$this->addMiniAction($OnlineSupportRequest);
		
		$infoSupportRequest = array(
				'module' => 'common',
				'controller' => 'block',
				'action' => 'infoSupport',
				'regionId' => 5,
				'boxWeight' => 3,
		);
		$this->addMiniAction($infoSupportRequest);
		
		$mapRequest = array(
                            'module' => 'hvn',
                            'controller' => 'block',
                            'action' => 'mapVietnam',
                            'regionId' => 6,
                            'boxWeight' => 1,
                );
		$this->addMiniAction($mapRequest);
*/
        $this->renderToHolder('index/new.phtml', false, null, 4, 1);    
	}
    
    public function deleteAction()
    {
    	if (!$id = $this->_request->getParam('id'))
    	{
    		$this->view->errorMessage = t(508);
    		$this->renderToHolder('common/error.phtml');
            return;
        }
        
        if ($this->m->deleteByPrimary(array($id)))
        {
            $this->view->operation = t(509);
            $this->renderToHolder('common/success.phtml');
        }
		else
		{   
			$this->view->errorMessage = t(510);
            $this->renderToHolder('common/error.phtml');
		}   
    }

    public function searchAction()
    {	
    	$data = $this->_request->getParams();
      	$form = new Form_Search();
      	$form->cluBuild(array ('view' => $this->view));
        $this->view->form = $form; 
		if($this->_request->isPost() && $form->isValid($_POST))
		{
	    	if($paginator = $this->m->search($data))
    		{
    			$paginator = $this->generatePaginator($paginator, 1, $data['articles_per_page'], 3, 'Jumping');
                $form->populate($data);  
    			
    			//cache in $_SESSION
               	$sess = new Zend_Session_Namespace("article_paginator");
                $sess->article_search_params = array("search_params" => $data); 
        	}
		}
        else if(!empty($data['page']) && $data['page'] != null){
			$sess = new Zend_Session_Namespace("article_paginator");
        	$data = $sess->article_search_params;
//    		die_a($data);
           	if(isset($data))
           	{
               $select = $this->m->search($data['search_params']);
               $paginator = $this->generatePaginator($select, $this->_getParam('page'), $data['search_params']['articles_per_page'], 3, 'Jumping');
               //populate form
               $form->populate($data['search_params']);
           	}
        }
        
        if(isset($paginator))
       	{      
           	//find translated languages list
        	$mTranslation = new article_Model_Translation();
            $translated = array();
            foreach ($paginator as $a)
            {
            	$res = $mTranslation->findTranslatedLanguagesList($a['article_id']);
            	$t = '';
            	foreach ($res as $translation)
                	$t = $translation['language'] . ", " . $t; 
                $translated[$a['article_id']] = $t;
            }
            $this->view->translated = $translated;
                  
            $this->view->paginator = $paginator;
    		$this->view->articleList = $paginator->getCurrentItems();//list of found articles
            $this->renderToHolder('index/list.phtml',false, null, 4,2); 
       	}
       	
       	$loginRequest = array(
                                'module' => 'user',
                                'controller' => 'block',
                                'action' => 'login',
                                'regionId' => 1,
                                'boxWeight' => 1,
								'theme' => 'second'
                );
		$this->addMiniAction($loginRequest);
		$OnlineSupportRequest = array(
				'module' => 'hvn',
				'controller' => 'block',
				'action' => 'onlineSupport',
				'regionId' => 5,
				'boxWeight' => 2,
		);
		$this->addMiniAction($OnlineSupportRequest);
		
		$infoSupportRequest = array(
				'module' => 'common',
				'controller' => 'block',
				'action' => 'infoSupport',
				'regionId' => 5,
				'boxWeight' => 3,
		);
		$this->addMiniAction($infoSupportRequest);
		
		$mapRequest = array(
                            'module' => 'hvn',
                            'controller' => 'block',
                            'action' => 'mapVietnam',
                            'regionId' => 6,
                            'boxWeight' => 1,
                );
		$this->addMiniAction($mapRequest);
		
        $this->renderToHolder('index/search.phtml',false, null, 4,1); //search box 
    }
    
	public function generatePaginator($select, $pageNumber, $itemsPerPage, $pageRange, $style)
    {
        $paginator = new Zend_Paginator(new Zend_Paginator_Adapter_DbSelect($select));
        $paginator->setItemCountPerPage($itemsPerPage);
        $paginator->setCurrentPageNumber($pageNumber);
        $paginator->setPageRange($pageRange);
        Zend_Paginator::setDefaultScrollingStyle($style);
        return $paginator;
    }
    
    public function bulkAction()
    {
        $ids = $this->_request->getParam('articles');
        if (count($ids) > 0)
        {
        	$action = $this->_request->getParam('bulkaction');
            if ($action === 'delete')
            {
                if ($this->m->deleteByPrimary($ids))
                {
                    $this->view->operation = t(509);
        		    $this->renderToHolder('common/success.phtml');
					return;
                }
            }
            else if ($action === 'status')
            {
            	$data = array();
            	$data['status'] = $this->_request->getParam('changestatus');
            	$data['statuschange_reason'] = $this->_request->getParam('reason');
				if ($this->m->bulkUpdateStatus($ids, $data))
				{
				    $this->view->operation = t(72);
				    $this->renderToHolder('common/success.phtml');
				    return;        
				}
            }
        }
        $this->view->errorMessage = t(73);
        $this->renderToHolder('common/error.phtml');  
    }
        
    public function translateAction()
    {
    	$id = $this->_request->getParam("id");
//		$tmp['language'] = $this->_request->getParam("to");
		
    	if (!$a = $this->m->findByPrimary($id))
        {                
            $this->view->errorMessage = t(504);
            $this->renderToHolder('common/error.phtml');
            return;
        }
        //get language
        $to = $this->_request->getParam('to');
        $this->view->id = $id;
        $this->view->a = $a;
//    	die_a($this->view->a);
        
        if(!$to)
        {
            $this->renderToHolder('index/chooselanguage.phtml');
        	return;
        }
        else 
        {
            $form = new article_Form_Translation();
            $form->cluBuild(array ('action' => 'translate','view' => $this->view));
        	$mTranslation = new article_Model_Translation();
          
    		if(!$t = $mTranslation->findByPrimary(array('id'=>$id,'language'=>$to)))
    		{
                $this->view->errorMessage = t(74);
                $this->view->act = 'new';
    		}
            else 
            {
                //article has been translated. Populate if first time (GET mode)
                if (!$this->_request->isPost())
                	$form->populate($t->toArray());
                $this->view->act = 'update';
            }
    	
          	if ($this->_request->isPost() && $form->isValid($_POST) )
    	    {
    	        $act = $this->_request->getParam('act');

    	        if ($act === 'new')
    	        {
    	            if ($mTranslation->insertRaw($this->_request->getParams()))
    	            {
        	            $this->view->action = t(75);
        	            $this->renderToHolder("common/success.phtml");
        	            return;
                    }
                    else 
                    {
                    	$this->view->errorMessage = t(74);
                    	$this->renderToHolder("common/error.phtml");
                    	return;
                    }
    	        }
    	        else if ($act === 'update')
    	        {
    	        	if ($mTranslation->saveRaw($t, $this->_request->getParams(), $id, $to, false))
    	        	{    	        	
        	            $this->view->action = t(76);
        	            /*
        	            $this->view->url = this->view->hvnUrl(array(
        	            	'lang' = $to;
        	            	'module' => 
        	            ));
        	            */
        	            $this->renderToHolder("common/success.phtml");
        	            return;
    	        	}
    	        }
    	     } 
			$this->view->form = $form;
            $this->view->id = $id;
            $this->view->to = $to;
        }
        $this->renderToHolder('index/translate.phtml');   
    }

    public function successAction()
    {
         $this->view->articleId =  $this->_request->getParam("lastInsertId");
         $this->renderToHolder('index/postSuccess.phtml');  
    }
}
?>
